#include <iostream>
#include <fstream>
#include "serverstat.h"


using namespace std;

/* This class accumulate and processing data which have been received from the
    remote agents */

ServerStat::ServerStat() : m_hosts(0), m_countOfElements(0), m_data(0), m_bot_host(0),
m_config(0)
{

        m_config = new CfgParser(1);
        if (m_config)
        {
                m_pool.host = m_config->getAgentHosts();
                m_pool.ip = m_config->getAgentIps();
                m_bot_host = m_config->getBotIp();
                m_countOfElements = m_pool.ip->size();
                for (int i = 0; i < m_countOfElements; ++i)
                        m_pool.state.push_back(1);

        }
        else exit(0);


}

ServerStat::~ServerStat()
{
        if (m_hosts)
                delete m_hosts;
        delete m_config;
}

//this function send requeset to the agent

bool ServerStat::request(const std::string &host, const string &command,
                         int port)
{
        //exception !!!
        if (!host.empty() && !command.empty())
        {
                SocketHandler h;
                ServerSocket cs(h);
                if (m_replyHandler)
                        cs.setReplyHandler(m_replyHandler);
                cs.setCommand(command);
                bool result = false;
                cs.Open(host, port);
                h.Add(&cs);
                h.Select(1, 0);
                while (h.GetCount())
                {
                        result = true;
                        h.Select(1, 0);
                }
                return result;
        }

        return false;
}

void ServerStat::listen()
{
        SocketHandler h;
        ListenSocket<AgentSocket> l(h, m_data);

        if (l.Bind(11001))
        {
                exit(-1);
        }
        h.Add(&l);
        h.Select(1, 0);
        while (h.GetCount())
        {
                h.Select(1, 0);
        }
}